import { type Product } from "wasp/entities";
import { HttpError } from "wasp/server";
import {
  type CreateProduct,
  type UpdateProduct,
  type DeleteProduct,
} from "wasp/server/operations";

// 新增商品
type CreateTaskPayload = Pick<
  Product,
  "name" | "category" | "price" | "stock" | "status"
>;

export const createProduct: CreateProduct<CreateTaskPayload, Product> = async (
  args,
  context
) => {
  if (!context.user) throw new HttpError(401);

  return context.entities.Product.create({
    data: {
      name: args.name,
      category: args.category,
      price: args.price,
      stock: args.stock,
      status: args.status,
      user: {
        connect: {
          id: context.user?.id,
        },
      },
    },
  });
};

// 更新商品
type UpdateTaskPayload = Pick<
  Product,
  "id" | "name" | "category" | "price" | "stock" | "status"
>;

export const updateProduct: UpdateProduct<UpdateTaskPayload, Product> = async (
  args,
  context
) => {
  if (!context.user) throw new HttpError(401);

  return context.entities.Product.update({
    where: {
      id: args.id,
    },
    data: {
      name: args.name,
      category: args.category,
      price: args.price,
      stock: args.stock,
      status: args.status,
    },
  });
};

// 删除商品
type DeleteTaskPayload = Pick<Product, "id">;

export const deleteProduct: DeleteProduct<DeleteTaskPayload, Product> = async (
  args,
  context
) => {
  if (!context.user) throw new HttpError(401);

  return context.entities.Product.delete({
    where: {
      id: args.id,
    },
  });
};
